using UnityEngine;
using System.Collections;
using System;
 
public class MeuServer : MonoBehaviour 
{

	public String IPServer = "127.0.0.1";
	public String IPServidor = "";
	
	void OnGUI()
	{
		if(Network.peerType == NetworkPeerType.Disconnected)
		{
			IPServer = GUI.TextField(new Rect(120,10,100,20),IPServer);
			
			if(GUI.Button(new Rect(10,10,100,30),"Conectar"))
			{
				Network.Connect(IPServer,25000);
				OnConnectedToServer();
			}
			if(GUI.Button(new Rect(10,50,100,30),"Iniciar Server"))
			{
				Network.InitializeServer(5,25000,false);
				GameObject[] gameObjects = FindObjectsOfType(typeof(GameObject)) as GameObject[];
				
				foreach(GameObject go in gameObjects)
				{
					go.SendMessage("noAr",SendMessageOptions.DontRequireReceiver);
				}
			}
		}
		
		else
		{
			if(Network.isServer)
			{
				IPServidor = Network.player.ipAddress;
				GUI.Label(new Rect(140,20,250,40),"Para jogar usar " + IPServidor);
			}
			
			if(GUI.Button(new Rect(10,10,100,30),"Sair"))
			{
				if(Network.isServer)
				{
					networkView.RPC("DesligarCL",RPCMode.Others,"Server Fechado");
				}
				if(Network.isClient)
				{
					OnPlayerDisconnected(Network.player);
				}
				Network.Disconnect();
				Application.Quit();
			}
		}
	}
	
	void OnConnectedToServer()
	{
		GameObject[] gameObjects = FindObjectsOfType(typeof(GameObject)) as GameObject[];
				
		foreach(GameObject go in gameObjects)
		{
			go.SendMessage("noAr",SendMessageOptions.DontRequireReceiver);
		}
	}
		
	void OnPlayerDisconnected (NetworkPlayer Player)
	{
		Network.RemoveRPCs(Player,0);
		Network.DestroyPlayerObjects(Player);
	}
	
	[RPC]
	void DesligarCL(String recebido)
	{
		Application.Quit();
	}	
	
	[RPC]
	void AnimaCL(String ent)
	{
 		var Player = GameObject.Find("Personagem"+ent+"(Clone)");
 		Player.animation.CrossFade("run");
 		Player.animation.wrapMode = WrapMode.Loop;
	}
  
	[RPC]
	void ParaCL(String ent)
	{
 		var Player = GameObject.Find("Personagem"+ent+"(Clone)");
		Player.animation.CrossFade("idle");
 		Player.animation.wrapMode =WrapMode.Once;
	}
}
